//
//  BankCardModel.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/25.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Alamofire

class BankCardModel: NSObject {
    var isDefault = false   //是否是选中状态
    var isStop = false      //这张卡是否已经解绑了，true是解绑
    var bankName: String?
    var salaryCardBankAccount: String?
    var bankCardId: String?
    required init(_ jsonData: [String: Any]) {
        if let isDefault = jsonData["IsDefault"], isDefault is Bool {
            self.isDefault = isDefault as! Bool
        }
        
        if let bankInfo = jsonData["BankInfo"] {
            if let bankInfoDic = bankInfo as? [String: Any], let bankName = bankInfoDic["BankName"] {
                self.bankName = bankName as? String
            }
        }
        
        if let account = jsonData["SalaryCardBankAccount"] {
            self.salaryCardBankAccount = account as? String
        }
        
        if let aId = jsonData["ID"] {
            self.bankCardId = aId as? String
        }
        
        if let isStop = jsonData["IsStop"] as? Bool {
            self.isStop = isStop
        }
    }
    
    //获取绑定的银行卡
    class func getBankCard(_ completionHandler:@escaping (WWValueResponse<[BankCardModel]>) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId, let companyId = model.companyId else {
            return
        }

        let method = "KouFine.Handler.Core.AjaxOperate.GetEntityOrderByOrderID"
        let pageName = "MarTian.Edit.GongZiKaWeiHu"
        let domain = "基础数据"
        let typeFullName = "MarTian.BasicEntity.CompanyMG"
        let orderConfigId = "317f45ba-8877-aca2-9892-5eec54f7f901"
        
        let params = ["Method":method, "pageName": pageName, "domain": domain, "typeFullName": typeFullName, "orderConfigId": orderConfigId, "orderID": companyId, "AccountId": accountId]
        
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let valueDic = response.result.value as? [String: Any] {
                    if let valueArr = valueDic["GongZiKaXinXi"] as? [[String: AnyObject]] {
                        var bankCardModels = [BankCardModel]()
                        
                        for item in valueArr {
                            let model = BankCardModel.init(item)
                            if model.isStop == false { //isStop表示这张卡解绑了。
                                bankCardModels.append(model)
                            }
                            
                        }
                        
                        completionHandler(WWValueResponse.init(value: bankCardModels, success: true))
                        return
                    }
                }
                completionHandler(WWValueResponse.init(success: false, message: "数据格式错误"))
            }
            else {
                
                completionHandler(WWValueResponse.init(success: false, message: "网络错误"))
            }
        }
    }
    
    
    /// 添加银行卡
    class func addBankCard(_ guid: String, cardId: String, bankId: String, completionHandler:@escaping (WWResponse) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId, let companyId = model.companyId else {
            return
        }
        
        let method = "KouFine.Handler.Core.AjaxOperate.SaveOrderData"
        let pageName = "MarTian.Edit.GongZiKaWeiHu"
        let orderConfigId = "317f45ba-8877-aca2-9892-5eec54f7f901"
        let operate = 2
        
        let bankInfo = ["ID":bankId]
        let gongZiKaXinXi = [["ID":guid, "SalaryCardBankAccount":cardId, "BankInfo": bankInfo, "Operate":1]]
        let jsonData = ["ID":companyId, "GongZiKaXinXi":gongZiKaXinXi] as [String : Any]
        let jsonDataString = getJSONStringFromDictionary(dictionary: jsonData as NSDictionary)
        
        let params = ["Method": method, "pageName":pageName, "orderConfigId": orderConfigId, "orderId": companyId, "jsonData":jsonDataString, "operate": operate, "AccountId": accountId] as [String : Any]
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseString { (response) in
            if response.result.isSuccess {
                if let value = response.result.value {
                    if value == "OK" {
                        completionHandler(WWResponse.init(success: true, message: "添加成功"))
                        return
                    }
                }
                completionHandler(WWResponse.init(success: false, message: "上传失败"))
            }
            else {
               
                completionHandler(WWResponse.init(success: false, message: "网络访问错误"))
            }
        }
    }
    
    //解绑银行卡
    class func removeBankCard(_ salaryCardId: String,completionHandler:@escaping (WWResponse) -> Void) {
        guard let httpHeader = WWUser.sharedInstance.mobile_cilent_headers else {
            return
        }
        guard let accountId = WWUser.sharedInstance.accountId else {
            return
        }
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxMigrantWorkerSalaryPayApply.RemoveSalaryCard"
        let params = ["Method": method, "SalaryCardID":salaryCardId, "AccountId":accountId]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    if let status = dict["Status"] as? String {
                        if status == "OK" {
                            completionHandler(WWResponse.init(success: true))
                            return
                        }
                    }
                }
                completionHandler(WWResponse.init(success: false, message: "未知错误"))
            }
            else {
                completionHandler(WWResponse.init(success: false, message: "网络访问错误"))
            }
        }
    }
    
    //默认银行卡更新
    class func updateDefaultBankCard(_ bankCardId: String, completionHandler: @escaping (WWValueResponse<String>) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId, let companyId = model.companyId else {
            return
        }
        
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxMigrantWorkerSalaryPayApply.SetSalaryCardSelectState"
        
        let params = ["Method": method, "SalaryCardID": bankCardId, "CompanyID": companyId, "Account": accountId]
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let value = response.result.value as? [String: AnyObject] {
                    let status = StatusStruct(rootJson: value)
                    if status.success {
                        completionHandler(WWValueResponse.init(value: status.statusString!, success: true))
                    }
                    else {
                        completionHandler(WWValueResponse.init(value: status.statusString!, success: false))
                    }
                }
            }
            else {
                
                completionHandler(WWValueResponse.init(success: false, message: "网络访问错误"))
            }
        }
    }
}

class BankModel {
    var bankName: String?
    var bankNo: Int?
    var isDisable: Bool?
    var bankId: String?
    
    required init(_ jsonData: [String: AnyObject]) {
        if let bankName = jsonData["BankName"] {
            self.bankName = bankName as? String
        }
        
        if let bankId = jsonData["ID"] {
            self.bankId = bankId as? String
        }
    }
    
    //获取各种银行的名字
    class func getBankNames(completionHandler: @escaping (WWValueResponse<[BankModel]>) -> Void) {
       // let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        
        let method = "KouFine.Handler.Core.AjaxOperate.FindPagingEntityData"
        let domain = "基础数据"
        let typeFullName = "MarTian.BasicEntity.BankNoInfo"
        let orderManagerConfigId = "bda6b713-cdc7-8466-8d76-9eb7eaf84380"
        let isQueryControl = "false"
        let sql = "IsDisable==@IsDisable"
        let pageName = "KouFine.Container.List"
        let controlName = ""
        let start = "0"
        let limit = "25"
        
        let items = [["Name":"@IsDisable", "type": "Boolean", "Value": "false"]]
        let sqlParam = ["Items": items]
        let sqlParamString = getJSONStringFromDictionary(dictionary: sqlParam as NSDictionary)
        
        let params = ["Method":method, "domain": domain, "typeFullName":typeFullName, "orderManagerConfigId": orderManagerConfigId, "isQueryControl":isQueryControl, "sql":sql, "sqlParam":sqlParamString, "pageName":pageName, "controlName": controlName, "AccountId":accountId, "start": start, "limit": limit] as [String : Any]
        
        Alamofire.request(LC_DetailUrl, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let value = response.result.value as? [String: AnyObject] {
                    if let items = value["Items"] as? [[String: AnyObject]] {
                        var bankArr = [BankModel]()
                        for item in items {
                            let model = BankModel.init(item)
                            bankArr.append(model)
                        }
                        completionHandler(WWValueResponse.init(value: bankArr, success: true))
                        return
                    }
                }
                completionHandler(WWValueResponse.init(success: false, message: "数据解析错误"))
            }
            else {
               
                completionHandler(WWValueResponse.init(success: false, message: "网络访问错误"))
            }
        }
    }

}
